package org.jsbd.boss.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsbd.boss.action.MiguVideoConfigController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;

/**
 * Created by dfzhang on 2018/6/7.
 */

public class ReadMGVideoPkg {

	private static final Logger LOGGER=LoggerFactory.getLogger(ReadMGVideoPkg.class);
	
    public static Map<String, String> readPackageInfo(String jarPath, String apkPath,String fileName){
        String versionCode = "unknown";
        String appVersion = "unknown";
        String appTextVersion = "unknown";
        String chanel = "unknown";
        String clientChannelId = "unknown";
        String logSDKVersion = "unknown";

        if(!apkPath.endsWith(".apk")){
            System.out.println("only .apk extension is supported!");
            return null;
        }
        //1. check if already decoded

      //3. read content
        System.out.println("11111111111111111111111111111111apkPath="+apkPath);
        String decodedDir = apkPath.substring(0, apkPath.length() - 4);
        System.out.println("22222222222222222222222222222222decodedDir="+decodedDir);
        
        //2. use apktool.jar
        System.out.println("begin decode apk file...");
        //Linux
        String decodeAPK = "java -jar "+jarPath+"/webapp/Apktool.jar -f d " + apkPath +" -o "+decodedDir;
        //Windows
        //String decodeAPK = "java -jar webapp" + File.separator + "Apktool.jar -f d " + apkPath +" -o "+decodedDir;
        System.out.println("33333333333333333333333333333333decodeAPK="+decodeAPK);
        try {
            Process process = Runtime.getRuntime().exec(decodeAPK);
            String line = "";

            //BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            //while ((line = stdoutReader.readLine()) != null) {
            //    System.out.println(line);
            //}
            while ((line = stderrReader.readLine()) != null) {
//                System.out.println(line);
           }
            int exitVal = process.waitFor();
            //System.out.println("process exit value is " + exitVal);

            System.out.println("Apk decode finish, begin read content....");
            //stdoutReader.close();
            stderrReader.close();
        } catch (IOException e) {
            System.out.println("Apktool exception occur...");
            e.printStackTrace();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        
        
        File decodeFile=new File(decodedDir);
        if(!decodeFile.exists()) {
        	decodeFile.mkdirs();
        }
        
        String apktoolYml = decodedDir + File.separator+"apktool.yml";

        //3.1  parse versionCode, appTextVersion, chanel
        List<String> apktoolStrings = readFileContent(apktoolYml);
        if(apktoolStrings.isEmpty()){
            System.out.println("can't read apktool.yml...");
        }else{
            for(String line : apktoolStrings){
                if(line.contains("versionCode")){
                    String []items = line.split(":");
                    String versonCodeString = items[1].trim();

                    versionCode = versonCodeString.substring(1, versonCodeString.length() - 1);
                }else if(line.contains("versionName")){
                    String []items = line.split(":");

                    appTextVersion = items[1].trim();
                }else if(line.contains("META-INF" + File.separator + "channel")){
                    String []items = line.split("_");

                    chanel = items[1];
                }
            }
        }

        //3.2 read chanel.ini
        String chanelini = decodedDir + File.separator + "assets" + File.separator + "channelid.ini";
        List<String> chanelStrings = readFileContent(chanelini);
        if(chanelStrings.isEmpty()){
            System.out.println("can't read file channelid.ini");
        }else{
            String item = chanelStrings.get(0).trim();
            String []items = item.split("-");

            appVersion = items[0];
            clientChannelId = item + "-" + chanel;
        }

        //3.3 read log sdk version
        String logSdkSmail="";
        for(int i=0;i<5;i++) {
        	logSdkSmail = decodedDir + File.separator + "smali_classes"+i+ File.separator + "com" + File.separator + "cmvideo"+File.separator+"analitics"+File.separator+"sdk"+File.separator+"BuildConfig.smali";
            File file=new File(logSdkSmail);
            if(file.isFile()&&file.exists()) {
            	break;
            }
        }
        
        List<String> logStrings = readFileContent(logSdkSmail);
        if(chanelStrings.isEmpty()){
            System.out.println("can't read migu log sdk version");
        }else{
            for(String line : logStrings){
                if(line.contains("VERSION_NAME:Ljava/lang/String")){
                    String []items = line.split("=");
                    String sdkVersion = items[1].trim();

                    logSDKVersion = sdkVersion.substring(1, sdkVersion.length() - 1);
                    break;
                }
            }
        }
        
        
        
        Map<String, String> map = new HashMap<String, String>();
        map.put("fileName", fileName);
        map.put("appVerion", appVersion);
        map.put("appVersionCode", versionCode);
        map.put("appTextVersion", appTextVersion);
        map.put("clientChanelId", clientChannelId);
        map.put("chanel", chanel);
        map.put("logSDKVersion", logSDKVersion);
        
        LOGGER.warn("Map:{}", new Object[] { map });
        
        return map;
    }
    
    public static List<String> readFileContent(String filePath){
        List<String> list = new ArrayList<>();
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;

                while ((lineTxt = bufferedReader.readLine()) != null) {
                    list.add(lineTxt);
                }
                bufferedReader.close();
                read.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
